import 'dart:async';

import 'package:flutter/material.dart';
import 'package:x3_base_core/base_enums/base_http_method_enum.dart';
import 'package:x3_base_core/base_models/base_screen_request_model.dart';
import 'package:x3_component_core/components/base_components/base_custom_checkbox_tile.dart';
import 'package:x3_component_core/components/base_components/base_text_field.dart';
import 'package:x3_component_core/components/expand_components/base_request_expandable_panel.dart';
import 'package:x3_component_core/components/layout_components/base_card_component.dart';
import 'package:x3_component_core/components/selector_components/sub_level_multi/base_sub_level_multi_selector.dart';
import 'package:x3_component_core/components/state_components/base_empty_component.dart';
import 'package:x3_component_core/models/base_custom_checkbox_tile_model.dart';
import 'package:x3_component_core/models/base_sub_level_multi_selector_model.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

/// 父级
class BaseSubLevelMultiItem extends StatefulWidget {
  /// 父级数据
  final BaseSubLevelMultiDataStore store;

  final Function(BaseSubLevelMultiSelectorModel) loadedCallBack;

  /// 数据装饰器
  final BaseCustomCheckboxListTileModel Function(dynamic) decorator;

  /// 子类数据装饰器
  final Widget Function(BaseCustomCheckboxListTileModel) itemWidgetDecorator;

  /// 是否采用静态数据
  final bool isStaticData;

  /// 是否搜索
  final bool isSearch;

  /// 重置数据
  final StreamController<List<BaseSubLevelMultiSelectorModel>> resetStreamController;
  @required
  final int index;
  BaseSubLevelMultiItem({
    Key key,
    @required this.store,
    this.decorator,
    this.itemWidgetDecorator,
    this.isStaticData = false,
    this.loadedCallBack,
    this.isSearch = false,
    this.resetStreamController,
    @required this.index,
  }) : super(key: key);
  @override
  _BaseSubLevelMultiItemState createState() => _BaseSubLevelMultiItemState();
}

class _BaseSubLevelMultiItemState extends State<BaseSubLevelMultiItem> {
  int get wIndex => widget.index;

  BaseSubLevelMultiSelectorModel _model;

  StreamController _streamController = StreamController<List<BaseCustomCheckboxListTileModel>>();

  /// 全选控制流
  StreamController _isAllStreamController = StreamController<bool>();

  /// 是否加载完毕
  bool _isLoad = false;

  /// 是否被重置
  bool _isReset = false;

  /// 控制器
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    _model = widget.store.dataSource[widget.index];

    /// 重置数据
    if (widget.resetStreamController != null) {
      widget.resetStreamController.stream.listen((event) {
        _isReset = true;
        if (!_streamController.isClosed) {
          _model.selectedChildrenKey.clear();
          if (_model.children.length > 0) {
            _model.children.forEach((element) {
              element.isChecked = false;
            });
            _streamController.sink.add(_model.children);
          }
          _onWatchAllState();
        }
      });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isStaticData == true) assert(_model.children.length > 0);
    return BaseCardComponent(
      child: BaseRequestExpandablePanel(
        dataSource: (_model.children != null && widget.isStaticData == true) ? _model.children : null,
        request: BaseScreenRequestModel(_model.inputApi, params: _model.params, method: BaseHttpMethodEnum.GET),
        header: _buildParentHeader(),
        builder: (result) => _buildExpandedContent(result),
      ),
    );
  }

  /// 父级头部
  Widget _buildParentHeader() {
    return Row(
      children: [
        AbsorbPointer(
          absorbing: widget.isStaticData == true ? false : !_isLoad,
          child: StreamBuilder<bool>(
            key: Key(_model.title),
            initialData: _model.isAll,
            stream: _isAllStreamController.stream,
            builder: (context, snapshot) {
              bool isAll = snapshot.data;
              return Checkbox(tristate: true, value: isAll, onChanged: _onChangeAll);
            },
          ),
        ),
        SizedBox(width: 12),
        Expanded(
          child: Text(
            _model.title,
            softWrap: false,
            overflow: TextOverflow.ellipsis,
            style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 15, fontWeight: FontWeight.w500),
          ),
        ),
      ],
    );
  }

  /// 构建子级内容
  Widget _buildExpandedContent(dynamic childrenData) {
    /// 加载完毕状态
    if (widget.isStaticData == false) {
      setState(() => {_isLoad = true});
      if (widget.loadedCallBack != null) widget.loadedCallBack(_model);
    }

    /// 验证初始化
    List _childrenData = List.from(childrenData);
    List<BaseCustomCheckboxListTileModel> datas = [];
    for (int i = 0; i < _childrenData.length; i++) {
      var item = _childrenData[i];
      BaseCustomCheckboxListTileModel child;

      /// 存在装饰器 调用装饰器方法

      if (widget.decorator != null) child = widget.decorator(item);
      if (item is BaseCustomCheckboxListTileModel) child = item;

      /// 检查已选的数据
      if (widget.decorator != null || item is BaseCustomCheckboxListTileModel) {
        child.key = i;

        /// 如果不存在被重置状态
        if (_isReset == false) {
          if (child.isChecked == true) _model.selectedChildrenKey.add(child.key);
        } else {
          child.isChecked = false;
        }
        datas.add(child);
        continue;
      }

      datas.add(BaseCustomCheckboxListTileModel.fromJson(item)..key = i);
    }
    _model.children = datas;

    /// 检查是否有选择默认值
    _onWatchAllState();

    /// 构建子item
    return Column(
      children: [
        Visibility(
          visible: widget.isSearch,
          child: Container(
            padding: EdgeInsets.only(left: 12),
            child: BaseTextField(
              // inputBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(3), borderSide: BorderSide(width: 0.8, color: BaseBodyTheme.iconColor)),
              hintText: '请输入关键字',
              textInputAction: TextInputAction.search,
              prefix: Icon(Icons.search_outlined, size: 18, color: Theme.of(context).inputDecorationTheme.hintStyle.color),
              onSubmitted: (v) => {_onSearch(v)},
              onClearOut: () => {_onSearch('')},
            ),
          ),
        ),
        StreamBuilder<List<BaseCustomCheckboxListTileModel>>(
          initialData: _model.children,
          stream: _streamController.stream,
          builder: (context, snapshot) {
            List<BaseCustomCheckboxListTileModel> datas = snapshot.data;
            if (datas == null && datas.length < 1) return BaseEmptyComponent();
            return Container(
              height: 280,
              child: ListView.separated(
                controller: _scrollController,
                physics: AlwaysScrollableScrollPhysics(),
                shrinkWrap: true,
                itemBuilder: (context, index) => _buildChildrenItem(datas[index], index),
                separatorBuilder: (_, __) => BaseComponentUtils.buildHorizontalDivider(),
                itemCount: datas.length,
              ),
            );
          },
        )
      ],
    );
  }

  /// 子item 容器
  Widget _buildChildrenItem(BaseCustomCheckboxListTileModel data, int index) {
    return BaseCustomCheckboxListTile(
      onChange: (v) => _onChangeChildrenItem(data: data, value: v),
      item: data,
      widgetDecorator: widget.itemWidgetDecorator,
    );
  }

  /// 勾选子item 事件
  void _onChangeChildrenItem({@required BaseCustomCheckboxListTileModel data, @required bool value}) {
    _model.children[data.key].isChecked = value;
    value == true ? _model.selectedChildrenKey.add(data.key) : _model.selectedChildrenKey.remove(data.key);
    _onWatchAllState();
  }

  /// 全选 / 反选
  void _onChangeAll(bool value) {
    _model.isAll = value ?? false;
    _model.children.forEach((element) {
      element.isChecked = _model.isAll;
      if (_model.isAll == true) _model.selectedChildrenKey.add(element.key);
    });
    if (_model.isAll == false) _model.selectedChildrenKey.clear();
    _streamController.sink.add(_model.children);
    _isAllStreamController.sink.add(_model.isAll);
  }

  /// 监视全选按钮状态
  void _onWatchAllState() {
    bool isAllSate;
    if (_model.children.length == _model.selectedChildrenKey.length) isAllSate = true;
    if (_model.selectedChildrenKey.length == 0) isAllSate = false;
    if (_model.isAll != isAllSate) {
      _model.isAll = isAllSate;
      _isAllStreamController.sink.add(_model.isAll);
    }
  }

  /// 搜索
  void _onSearch(String v) {
    if (v.isNotEmpty) {
      var list = _model.children.where((element) => element.title.contains(v)).toList();
      _streamController.sink.add(list);
    } else {
      _streamController.sink.add(_model.children);
    }
    _scrollController.animateTo(0, duration: Duration(milliseconds: 300), curve: Curves.ease);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _streamController.close();
    _isAllStreamController.close();
    super.dispose();
  }
}
